import {
	MP_API_URL,
	TOKEN_NAME,
	APP_ID
} from 'config.js';

/**
 * http 请求类
 * params：
 * param 请求参数
 */
export function request(params) {
	let url = MP_API_URL + params.url;
	params.type = params.type || 'get';
	/*不需要再次组装地址*/
	if (params.setUpUrl == false) {
		url = params.url;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: params.data,
			method: params.method,
			header: {
				'content-type': 'application/json',
				'Authorization': "Bearer "+ uni.getStorageSync(TOKEN_NAME)
			},
			success: async (res) => {
				console.log(res)
				var code = res.data.code;
				if (code == '1') {
					resolve(res.data);
				} else {
					//token已经过期了，需要重新获取
					if (res.statusCode == '401') {
						await getTokenFromServer();
						try {
							const again_request_data = await request(params);
							resolve(again_request_data)
						} catch (again_request_err) {
							// console.log(again_request_err);
							reject(again_request_err)
						}

					}
					_processError(res);
					reject(res.data);
				}
			},
			fail: (err) => {
				//wx.hideNavigationBarLoading();
				_processError(err);
				reject(err);
			}
		});
	})
}

/**
 * 从服务器中获取Token
 */
function getTokenFromServer() {
	return new Promise((resolve, reject) => {
		// uni.login({
		// 	provider: 'weixin',
		// 	success: (res) => {
		uni.request({
			url: MP_API_URL + 'login/refresh-token',
			method: 'POST',
			data: {
				AppId: APP_ID,
				Token: uni.getStorageSync(TOKEN_NAME)
			},
			success: (res) => {
				uni.setStorageSync(TOKEN_NAME, res.data.token); //将Token存放在本地
				resolve(res.data.token);
			}
		})
		// 	}
		// })
	})
}

/**
 * 处理错误
 */
function _processError(err) {
	// 判断错误的信息是什么类型
	let msg = [];
	if (err && err.data && typeof err.data.msg == 'object') {
		for (let item in err.data.msg) {
			msg.push(err.data.msg[item]);
		}
	} else if (err && err.data && typeof err.data.msg == 'string') {
		msg.push(err.data.msg);
	} else {
		msg.push('未知错误');
	}
	console.log(msg[0]);

	uni.showToast({
		title: msg[0],
		icon: 'none'
	});
}
